package com.controller;

import com.alibaba.fastjson.JSON;
import com.doMain.TableVO;
import com.pojo.SysRole;
import com.pojo.SysUser;
import com.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/sysRole")
public class SysRoleController {
    @Autowired
    private SysRoleService service;

    @GetMapping("/toList")
    public String toList(){
        return "roleList";
    }

    @GetMapping(value = "list",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(String roleName, Integer page, Integer limit){
        List<SysRole> list=service.list(roleName,page,limit);
        int count=service.count(roleName);
        TableVO tableVO = new TableVO(0,count,list,"");
        String json= JSON.toJSONString(tableVO);
        return json;
    }

    @GetMapping("/toRoleAdd")
    public String toAdd(){
        return "roleAdd";
    }

    @PostMapping(value = "/add",produces = "application/json;charset=utf-8")
    public String add(Model model,SysRole sysRole){
        int add=service.add(sysRole);
        if (add>0) {
            return "redirect:toList";
        }
        model.addAttribute("errorMsg","新增失败");
        return "roleAdd";
    }

    @GetMapping("/view/{roleId}")
    public String view(Model model,@PathVariable("roleId") Integer id){
        SysRole sysRole=service.selectId(id);
        model.addAttribute("role",sysRole);
        return "roleView";
    }

    @GetMapping("/toEdit/{roleId}")
    public String toEdit(Model model,@PathVariable("roleId") Integer id){
        SysRole role=service.selectId(id);
        model.addAttribute("role",role);
        return "roleEdit";
    }

    @GetMapping(value = "/edit",produces = "application/json;charset=utf-8")
    @ResponseBody
    public void edit(HttpServletResponse response, SysRole sysRole) throws IOException {
        int result=service.edit(sysRole);
        if (result>0) {
            response.getWriter().print("1");
        }
        else {
            response.getWriter().print("0");
        }
    }

    @GetMapping("/delete/{roleId}")
    @ResponseBody
    public String del(HttpServletResponse response,@PathVariable("roleId") Integer id) throws IOException {
        int del=service.del(id);
        return del>0?"1":"0";
    }
}
